package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    //套餐业务层
    @Autowired
    SetmealService setmealService;
    //套餐菜品业务层
    @Autowired
    SetmealDishService setmealDishService;
    //引入分类管理业务层
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishService dishService;

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        //创建分页构造器
        Page<Setmeal> pageInfo = new Page<>();
        //创建条件构造器
        LambdaQueryWrapper<Setmeal> slqw = new LambdaQueryWrapper<>();
        //设置模糊查询的条件
        slqw.like(StringUtils.isNotEmpty(name), Setmeal::getName, name);
        //设置排序，sort相同的情况下，再根据修改时间倒序排序
        slqw.orderByDesc(Setmeal::getUpdateTime);
        //执行语句
        setmealService.page(pageInfo, slqw);
        //最后返回的对象
        Page<SetmealDto> result = new Page<>();
        //吧查询出来的dish菜品中的数据拷贝到最后要返回的对象中，除了records
        BeanUtils.copyProperties(pageInfo, result, "records");
        //根据Dish菜品查询出来的数据集合
        List<Setmeal> records = pageInfo.getRecords();
        //获取数据集合中所有分类的id，放入一个新的集合
        List<Long> collectList = records.stream().map(Setmeal::getCategoryId).collect(Collectors.toList());
        //根据id集合查询出菜品分类集合
        List<Category> categories = categoryService.listByIds(collectList);
        //根据查询出来的菜品分类集合，放入map集合中
        Map<Long, String> collect = categories.stream().collect(Collectors.toMap(Category::getId, Category::getName));
        //封装到DishDto集合中
        List<SetmealDto> resultList = records.stream().map(setmeal -> {
            //创建一个空的dishDto对象
            SetmealDto setmealDto = new SetmealDto();
            //拷贝属性
            BeanUtils.copyProperties(setmeal, setmealDto);
            //在map集合中查询分类信息
            String catName = collect.get(setmeal.getCategoryId());
            //设置分类名称
            setmealDto.setCategoryName(catName);
            return setmealDto;
        }).collect(Collectors.toList());
        //吧数据封装到最终返回对象Records中
        result.setRecords(resultList);
        //返回最终对象
        return R.success(result);
    }

    //新增套餐
    @PostMapping
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        //记录套餐信息日志
        log.info("套餐信息:{}", setmealDto);
        //执行保存套餐信息，保存套餐和套餐菜品关系
        setmealService.saveWithDish(setmealDto);

        return R.success("添加套餐成功");
    }

    //状态
    @PostMapping("/status/{zt}")
    public R<String> status(@PathVariable String zt, @RequestParam List<Long> ids) {
        List<Setmeal> setmeals = setmealService.listByIds(ids);
        if (zt.equals("1")) {
            for (Setmeal setmeal : setmeals) {
                setmeal.setStatus(1);
            }
        } else if (zt.equals("0")) {
            for (Setmeal setmeal : setmeals) {
                setmeal.setStatus(0);
            }
        }else {
            return R.error("url错误");
        }
        setmealService.updateBatchById(setmeals);
        return R.success("修改状态成功");
    }

    //删除
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {
        //打印删除成功日志
        log.info("ids:{}", ids);

        //判断是否为空
        if (ids.isEmpty()) {
            return R.error("没有选择删除的套餐");
        }
        //执行删除方法
        setmealService.removeWithDish(ids);

        //删除成功后返回
        return R.success("套餐数据删除成功");
    }

    //根据id查询菜品及菜品口味信息
    @GetMapping("/{id}")
    public R<SetmealDto> get(@PathVariable Long id){
        //根据id查询菜品及菜品口味信息
        SetmealDto setmealDto=setmealService.getByIdWithFlavor(id);
        //返回查询出的结果
        return R.success(setmealDto);
    }

    //修改
    //修改菜品
    @PutMapping
    public R<String> update(@RequestBody SetmealDto setmealDto){
        //记录要修改的对象日志
        log.info(setmealDto.toString());
        setmealService.updateWithFlavor(setmealDto);
        return R.success("修改菜品成功");
    }

    @GetMapping("/list")
    public R<List<Setmeal>> list(Setmeal setmeal){
        LambdaQueryWrapper<Setmeal> slqw = new LambdaQueryWrapper<>();
        slqw.eq(setmeal.getCategoryId()!=null,Setmeal::getCategoryId,setmeal.getCategoryId());
        slqw.eq(setmeal.getStatus()!=null,Setmeal::getStatus,setmeal.getStatus());
        slqw.orderByDesc(Setmeal::getUpdateTime);
        List<Setmeal> list = setmealService.list(slqw);
        return R.success(list);
    }

    @GetMapping("/dish/{id}")
    public R<List<DishDto>> dish(@PathVariable Long id){

        Setmeal byId = setmealService.getByIdWithFlavor(id);

        LambdaQueryWrapper<SetmealDish> slqw = new LambdaQueryWrapper<>();
        slqw.eq(SetmealDish::getSetmealId,byId.getId());
        List<SetmealDish> list = setmealDishService.list(slqw);

        List<DishDto> dishDtos=list.stream().map(setmealDish -> {
            LambdaQueryWrapper<Dish> dlqw = new LambdaQueryWrapper<>();
            dlqw.eq(Dish::getId,setmealDish.getDishId());
            Dish dish = dishService.getOne(dlqw);
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish,dishDto);
            dishDto.setCopies(setmealDish.getCopies());
            return dishDto;
        }).collect(Collectors.toList());
        return R.success(dishDtos);
    }
}
